package com.ym.controller;

import com.baidu.aip.face.AipFace;
import com.ym.entity.User;
import com.ym.service.IFaceService;
import com.ym.utils.GetTon;
import com.ym.utils.GsonUtils;
import com.ym.utils.HttpUtil;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author: likang
 * @date: 2020/1/8 10:30
 * @description: 人脸注册
 */
@Controller
public class RegisteController {

    @Autowired
    IFaceService faceService;

    private static String accessToken;

    @Value("${myj.baidu.APPID}")
    private String APPID;
    @Value("${myj.baidu.APIKEY}")
    private String APIKEY;
    @Value("${myj.baidu.SECRETKEY}")
    private String SECRETKEY;
    @Value("${myj.baidu.faceset.URL}")
    private String URL;
    @Value("${myj.baidu.search.URL}")
    private String SEARCHURL;

    /*
     * @Description: 用户人脸识别头像录入(每个用户建议只允许录入一次)
     * @author: likang
     * @date: 2020/1/8 10:49
     * @params: [request, response, model]
     * @return: void
     * @exception:
     */
    @RequestMapping("/registe.action")
    public @ResponseBody void registe(HttpServletRequest request, HttpServletResponse response, Model model) {
        String img = request.getParameter("img"); // 图像数据
        String username = request.getParameter("username"); // 用户名
        // 注册百度云 人脸识别 提供的信息
        AipFace client = new AipFace(APPID, APIKEY, SECRETKEY);
        face(username, img, response, request, client);
    }

    /**
     *
     * @author: likang
     * @date: 2020/1/8 10:57
     * @description: 1.将base64编码的图片保存  2.将图片路径保存在数据库里面 3.将人脸图片识别在人脸库中注册
     */
    public void face(String username, String img, HttpServletResponse response, HttpServletRequest request,
                     AipFace client) {
        User user = new User();
        // 图片名称
        String fileName = System.currentTimeMillis() + ".png";
        String basePath = request.getSession().getServletContext().getRealPath("picture/");

        // 往数据库里面插入注册信息
        user.setUsername(username);
        user.setHeadphoto("/picture/" + fileName);
        faceService.save(user);
        // 往服务器里面上传图片
        GenerateImage(img, basePath + "/" + fileName);
        // 给人脸库中加入一个脸
        boolean flag = facesetAddUser(client, fileName, username,img);
        try {
            PrintWriter out = response.getWriter();
             if (flag == false) {
                out.print("qing ba lian fang hao le!!");// 请把脸放好咯
            } else {
                out.print("zhu ce cheng gong!!"); // 注册成功
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * @Description: 生成jpeg图片
     * @author: likang
     * @date: 2020/1/8 14:09
     * @params: [imgStr, imgFilePath]
     * @return: boolean
     * @exception:
     */
    public boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) { // 图像数据为空
            return false;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decode(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public boolean facesetAddUser(AipFace client, String path, String username, String img) {

         try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", img);
            map.put("group_id", "group_repeat");
            map.put("user_id", "user1");
            map.put("user_info", username);
            map.put("liveness_control", "NORMAL");
            map.put("image_type","BASE64");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);

            // 过期后重新获取。
            accessToken = GetTon.getToken();

            String result = HttpUtil.post(URL, accessToken, "application/json", param);
            System.out.println(result);

            JSONObject fromObject = JSONObject.fromObject(result);

            Object errormsg = fromObject.get("error_msg");
            if (errormsg.toString().equals("SUCCESS")) {
                return true;
            }
            return false;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean search(String img) {
        // 请求url
         try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", img);
            map.put("liveness_control", "NORMAL");
            map.put("group_id_list", "group_repeat");
            map.put("image_type", "BASE64");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);

            //过期后重新获取。
            accessToken = GetTon.getToken();

            String result = HttpUtil.post(SEARCHURL, accessToken, "application/json", param);
            System.out.println(result);

            JSONObject fromObject = JSONObject.fromObject(result);
            JSONObject resultscore = fromObject.getJSONObject("result");
            JSONArray jsonArray = resultscore.getJSONArray("user_list");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = (JSONObject) jsonArray.get(i);
                double resultList = object.getDouble("score");
                System.out.println(resultList);
                if (resultList >= 90) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
